#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <signal.h>
#include<linux/input.h>

#define CLOSE_CMD _IO(0x02,1)
#define OPEN_CMD _IO(0x02,2)
#define MODIFY_CMD _IO(0x02,3)

static int fd;
static struct input_event input;

void signal_func(int num)
{
    char buff = 0;
    read(fd,&buff,1);
    printf("read data:%d\r\n",buff);
}


int main(int argc ,char *argv[])
{
    int op_mod = 3;
    fd = open("/dev/input/event2",O_RDWR);  
    if(fd<0)
    {
        printf("open error!\r\n");
        return -1;
    }

    fd_set set;

    int ret = 0;

    if(op_mod==2)
    {
        signal(SIGIO,signal_func);
        fcntl(fd, F_SETOWN, getpid());
        int flags = fcntl(fd, F_GETFL, 0);
        fcntl(fd, F_SETFL, flags|FASYNC);
    }

    while(1)
    {
        if(op_mod == 0)
        {
            FD_ZERO(&set);
            FD_SET(fd,&set);
            struct timeval t;
            t.tv_sec=1;
            t.tv_usec=0;
            
            ret  = select(fd+1,&set,NULL,NULL,&t);
            switch (ret)
            {
            case 0:
                printf("time out !\r\n");
                break;
            case -1:
                printf("error\r\n");
                break;
            default:
                if(FD_ISSET(fd,&set))
                {
                    char buff;
                    read(fd,&buff,1);
                    printf("read data:%d\r\n",buff);
                }
                break;
            }
        }
        else if(op_mod == 1)
        {
            char buff = 0;
            ret = read(fd,&buff,1);
            if(ret>=0)
                printf("read data:%d\r\n",buff);
        }
        else if(op_mod == 2)
        {
            sleep(1);
        }
        else if (op_mod ==3)
        {
            ret = read(fd,&input,sizeof(input));
            if(ret<0)
            {
                printf("read error!\r\n");
                continue;
            }
            if(input.code==KEY_0)
            {
                if(input.value==1)
                    printf("press  time:s=%d us=%d\r\n",input.time.tv_sec,input.time.tv_usec);
                else if(input.value==0)
                    printf("release\r\n");
                else if(input.value==2)
                    printf("long press keyType=0x%x\r\n",input.code);
            }
            
        }
        
    }
    close(fd);
    return 0;
}